#pragma once

#include <iostream>
#include <sys/types.h>
#include <sys/ipc.h>
#include <cstdlib>
#include <cerrno>
#include <cstring>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <unistd.h>

using namespace std;

const char *pathname = "/home/tww";
const int proj_id = 0x66;
const int defaultsize = 4096; // 单位字节

string ToHex(key_t key)
{
    char buffer[1024];
    snprintf(buffer, sizeof(buffer), "%x", key);
    return buffer;
}

key_t GetShmKeyOrDie()
{
    key_t key = ftok(pathname, proj_id);
    if (key < 0)
    {
        cerr << "ftok failed errno:" << errno << ", errstring:" << strerror(errno) << endl;
        exit(1);
    }

    return key;
}

int CreateShmOrDie(key_t key, size_t size, int flag)
{
    int shmid = shmget(key, size, flag);
    if (shmid < 0)
    {
        cerr << "shmget failed errno:" << errno << ", errstring:" << strerror(errno) << endl;
        exit(2);
    }
    return shmid;
}

int CreateShm(key_t key, size_t size)
{
    // IPC_CREAT:无就创建，有就获取
    // IPC_EXCL:无意义
    // IPC_CREAT|IPC_EXCL：无就创建，有就出错返回
    return CreateShmOrDie(key, size, IPC_CREAT | IPC_EXCL | 0666);
}

int GetShm(key_t key, size_t size)
{
    return CreateShmOrDie(key, size, IPC_CREAT);
}

void DeleteShm(int shmid)
{
    int n = shmctl(shmid, IPC_RMID, nullptr);
    if (n < 0)
    {
        cerr << "delete  failed " << endl;
    }
    else
    {
        cout << "delete shm succsee,shmid:" << shmid << endl;
    }
}

void DebugShm(int shmid)
{
    struct shmid_ds shmds;
    shmctl(shmid, IPC_STAT, &shmds);
    cout << shmds.shm_segsz << endl;
    cout << shmds.shm_ctime << endl;
    cout << ToHex(shmds.shm_perm.__key) << endl;
}

void *AttachShm(int shmid)
{
    void *addr = shmat(shmid, nullptr, 0);
    if ((long long int)addr == -1)
    {
        cerr << "attach Shm failed " << endl;
        return nullptr;
    }

    return addr;
}

void DetachShm(void *addr)
{
    int n = shmdt(addr);
    if (n < 0)
    {
        cerr << "attach Shm failed " << endl;
    }
    else
    {
        cout << "detach Shm success" << endl;
    }
}